package com.inspectortime.webapp;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.inspectortime.repository.Repository;
import com.inspectortime.service.ZipCodeInfo;
import com.inspectortime.service.ZipCodeSearchService;
import com.mkode.util.java.lang.CollectionUtils;

/**
 * 
 * @author mkvalsvik
 * 
 */
public class FindInspectorByZipSearchController implements Controller {

	private ZipCodeSearchService zipCodeSearchService;
	
	private static Log log = LogFactory
			.getLog(FindInspectorByZipSearchController.class);

	private Repository repository;
	private String successView;

	public void setSuccessView(String successView) {
		this.successView = successView;
	}

	public FindInspectorByZipSearchController() {
		super();
	}

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response)
			throws Exception {

		String zip = request.getParameter("zip");
		String distance = request.getParameter("distance");
		int radius = Integer.parseInt(distance);

		List<ZipCodeInfo> zipInfoList = this.zipCodeSearchService.findNearbyZipCodes(zip, radius);
		List<String> zipCodeList = CollectionUtils.extractUniquePropertyList(zipInfoList, "zipCode");
		List companyList = Collections.EMPTY_LIST;
		if (!zipCodeList.isEmpty()) {
			companyList = repository.findInspectorCompaniesByZipCode(zipCodeList);	
		}		
		
		// Create a map of distances for the view layer to use
		Map<String, Double> distancesByZip = new HashMap<String, Double>();
		for (ZipCodeInfo info : zipInfoList) {
			distancesByZip.put(info.getZipCode(), info.getOptionalDistanceToSource());
		}		

		ModelAndView mv = new ModelAndView(this.successView);
		mv.addObject("companies", companyList);
		mv.addObject("distancesByZip", distancesByZip);
		mv.addObject("originalZip", zip);
		return mv;

	}

	public void setRepository(Repository repository) {
		this.repository = repository;
	}

	public void setZipCodeSearchService(ZipCodeSearchService zipCodeSearchService) {
		this.zipCodeSearchService = zipCodeSearchService;
	}
	
}
